public class FinalizeEscapeGC {
    private static FinalizeEscapeGC SAVE_HOOK = null;

    public static FinalizeEscapeGC getSaveHook() {
        return SAVE_HOOK;
    }

    public static void setSaveHook(FinalizeEscapeGC saveHook) {
        SAVE_HOOK = saveHook;
    }

    public void isAlive() {
        System.out.println("yes, i am still alive");
    }

    // 任何一个对象的finalize()方法都只会被系统自动调用一次，如果对象面临下一次回收，它的
    // finalize()方法不会被再次执行，因此第二段的自救行动失败了
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize method executed");
        FinalizeEscapeGC.SAVE_HOOK = this;
    }

    public static void main(String[] args) throws Throwable {
        SAVE_HOOK = new FinalizeEscapeGC();
        SAVE_HOOK = null;
        System.gc();
        // 因为 finalize()方法优先级很低，暂停0.5秒，以等待它
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("no, i am dead");
        }

        // 下面这段代码与上面的完全相同，但是这次自救却失败了
        SAVE_HOOK = null;
        System.gc();
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("no, i am dead");
        }
    }
}
